<template>
  <div class="singleImageUpload2" style="float: right">
    <el-upload
      ref="upload"
      :action="action"
      :before-upload="beforeUpload"
      class="image-uploader"
      :disabled="disabled"
      :drag="displayType !== 'button'"
      :field-name="fieldName"
      :file-list="fileList"
      :headers="headers"
      :limit="1"
      :multiple="false"
      :name="name"
      :on-error="onError"
      :on-exceed="onExceed"
      :on-remove="onRemove"
      :on-success="onSuccess"
      show-file-list
    >
      <el-button
        v-if="displayType === 'button'"
        size="small"
        style="margin-left: auto"
        type="primary"
      >
        载入文件
      </el-button>
      <div v-else class="upload-container">
        <i class="el-icon-upload" />
        <div v-if="fileList.length === 0" class="el-upload__text">
          请将文件拖入或
          <em>载入文件</em>
        </div>
        <div v-else class="el-upload__text">文件已上传</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
  export default {
    name: 'FileUpload',
    props: {
      displayType: {
        type: String,
        default() {
          return 'button'
        },
      },
      fieldName: {
        type: String,
        default() {
          return ''
        },
      },
      fileList: {
        type: Array,
        default() {
          return []
        },
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      action: {
        type: String,
        default() {
          return `http://api.zesi.com.cn/api/file/upload`
        },
      },
      name: {
        type: String,
        default() {
          return 'segment'
        },
      },
    },
    data() {
      return {
        token: '',
      }
    },
    computed: {
      headers() {
        return {
          token: this.token,
        }
      },
    },
    methods: {
      onRemove() {
        this.$message({
          message: '文件删除成功',
          type: 'success',
        })
        this.$emit('onRemove')
      },
      onExceed() {
        this.$message({
          message: '每次只能上传一个文件',
          type: 'warning',
        })
      },
      beforeUpload(file) {
        this.$emit('beforeUpload', file)
      },
      onSuccess(response, file) {
        this.$refs.upload.clearFiles()
        this.$emit('onSuccess', response, file)
      },
      onError(err) {
        console.log(err)
        const errMsg = (err.message && JSON.parse(err.message)) || '上传失败'
        this.$message({
          message:
            (errMsg.msg && `上传失败，失败原因：${errMsg.msg}`) || '上传失败',
          type: 'error',
        })
        this.$emit('onError', err)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .upload-container {
    position: relative;
    width: 100%;
    height: 100%;
    .image-uploader {
      height: 100%;
    }
  }
</style>
